/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller.security;

import com.thienloc.omap.controller.BaseBean;
import com.thienloc.omap.entity.OmapResource;
import com.thienloc.omap.entity.OmapRole;
import com.thienloc.omap.entity.OmapUser;
import com.thienloc.omap.entity.Permission;
import com.thienloc.omap.session.OmapRoleFacade;
import com.thienloc.omap.session.OmapUserFacade;
import com.thienloc.omap.session.PermissionFacade;
import com.thienloc.omap.session.ResourceFacade;
import com.thienloc.omap.util.JsfUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class PermissionBean extends BaseBean implements Serializable {

    @EJB
    private PermissionFacade facade;
    @EJB
    private OmapUserFacade omapUserFacade;
    @EJB
    private OmapRoleFacade omapRoleFacade;
    @EJB
    private ResourceFacade resourceFacade;
    private Logger logger = LoggerFactory.getLogger(PermissionBean.class);
    private List<Permission> list;
    private List<OmapRole> allRoles;
    private List<OmapUser> allUsers;
    private Permission selected;
    private Map<String, String> idMap;
    private String selectedCriteria;
    private String selectedId;
    private final String BY_USER = "byUser";
    private final String BY_ROLE = "byRole";
    private final String BY_RESOURCE = "byResource";
    private boolean editMode = true;

    @PostConstruct
    public void init() {
        try {
            selected = new Permission();
            list = new ArrayList<Permission>();
            allRoles = omapRoleFacade.findAll();
            allUsers = omapUserFacade.findAll();
            selectedCriteria = BY_RESOURCE;
            editMode = false;
            onCriteriaSelect();
        } catch (Exception ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi", ex.getMessage());
        }
    }

    public void prepareEdit() {
        editMode = true;
    }

    public void editSelected() {
        try {
            facade.edit(selected);
            for (OmapUser omapUser : selected.getOmapUserList()) {
                if (omapUser.getUserId() == sessionBean.getOmapUser().getUserId()) {
                    sessionBean.addPermission(selected.getResourceId().getName(), selected.getAction());
                    break;
                }
            }

            for (OmapRole omapRole : selected.getOmapRoleList()) {
                List<OmapRole> activeRoles = sessionBean.getOmapUser().getOmapRoleList();
                for (OmapRole activeRole : activeRoles) {
                    if (omapRole.getRoleId() == activeRole.getRoleId()) {
                        sessionBean.addPermission(selected.getResourceId().getName(), selected.getAction());
                    }
                }
            }
            editMode = false;
            logger.debug("[{}] Edited permission {}", getUsername(), selected.getId());
            JsfUtil.addSuccessMessage("Thành công", "Đã sửa thành công 1 bản ghi");
        } catch (Exception ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi", ex.getMessage());
        }
    }

    public void onCriteriaSelect() {
        if (selectedCriteria.equals(BY_USER)) {
            try {
                List<OmapUser> omapUsers = omapUserFacade.findAll();
                idMap = new TreeMap<String, String>();
                for (OmapUser omapUser : omapUsers) {
                    idMap.put(omapUser.getUsername(), String.valueOf(omapUser.getUserId()));
                }
            } catch (Exception ex) {
                logger.error("[{}]: ", getUsername(), ex);
            }
        } else if (selectedCriteria.equals(BY_ROLE)) {
            try {
                List<OmapRole> omapRoles = omapRoleFacade.findAll();
                idMap = new TreeMap<String, String>();
                for (OmapRole roles : omapRoles) {
                    idMap.put(roles.getRoleName(), String.valueOf(roles.getRoleId()));
                }
            } catch (Exception ex) {
                logger.error("[{}]: ", getUsername(), ex);
            }
        } else if (selectedCriteria.equals(BY_RESOURCE)) {
            try {
                List<OmapResource> resources = resourceFacade.findAll();
                idMap = new TreeMap<String, String>();
                for (OmapResource resource : resources) {
                    idMap.put(resource.getName(), String.valueOf(resource.getId()));
                }
            } catch (Exception ex) {
                logger.error("[{}]: ", getUsername(), ex);
            }
        }
    }

    public void viewPermission() {
        editMode = false;
        if (selectedCriteria.equals(BY_USER)) {
            list = facade.findByUserId(Integer.parseInt(selectedId));
//            List<OmapRole> roles = sessionBean.getOmapUser().getOmapRoleList();
//            
//            for (OmapRole omapRole : roles) {
//                List<Permission> rolePermissions = facade.findByRoleId(omapRole.getRoleId());
//                for (Permission rolePermission : rolePermissions) {
//                    
//                    boolean found = false;
//                    for (Permission alreadyKnownPermission : list) {
//                        if (alreadyKnownPermission.getResourceId().getName()
//                                .equals(rolePermission.getResourceId().getName())){
//                            if (alreadyKnownPermission.getAction().equals(rolePermission.getAction())){
//                                found = true;
//                                break;
//                            }
//                        }
//                    }
//                    
//                    if (!found) {
//                        list.add(rolePermission);
//                    }
//                }
//            }

        } else if (selectedCriteria.equals(BY_ROLE)) {
            list = facade.findByRoleId(Integer.parseInt(selectedId));

        } else if (selectedCriteria.equals(BY_RESOURCE)) {
            list = facade.findByResourceId(Integer.parseInt(selectedId));

        }
    }

    public List<Permission> getList() {
        return list;
    }

    public void setList(List<Permission> list) {
        this.list = list;
    }

    public Permission getSelected() {
        return selected;
    }

    public void setSelected(Permission selected) {
        this.selected = selected;
    }

    public String getSelectedCriteria() {
        return selectedCriteria;
    }

    public void setSelectedCriteria(String selectedCriteria) {
        this.selectedCriteria = selectedCriteria;
    }

    public Map<String, String> getIdMap() {
        return idMap;
    }

    public void setIdMap(Map<String, String> idMap) {
        this.idMap = idMap;
    }

    public String getSelectedId() {
        return selectedId;
    }

    public void setSelectedId(String selectedId) {
        this.selectedId = selectedId;
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public List<OmapRole> getAllRoles() {
        return allRoles;
    }

    public void setAllRoles(List<OmapRole> allRoles) {
        this.allRoles = allRoles;
    }

    public List<OmapUser> getAllUsers() {
        return allUsers;
    }

    public void setAllUsers(List<OmapUser> allUsers) {
        this.allUsers = allUsers;
    }
}
